package com.jourwon.spring.boot.response;

import com.alibaba.fastjson.annotation.JSONField;
import com.jourwon.spring.boot.constant.SysConstants;
import com.jourwon.spring.boot.enums.ResponseCodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.MDC;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 响应结果对象
 *
 * @author JourWon
 * @date 2021/1/21
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "ResponseStatus-响应结果对象")
public class ResponseStatus<T> implements Serializable {

    private static final long serialVersionUID = -1338376281028943181L;

    @ApiModelProperty(value = "操作结果码")
    private String code;

    @ApiModelProperty(value = "操作结果说明")
    private String message;

    @ApiModelProperty(value = "具体结果数据")
    private T data;

    @ApiModelProperty(value = "链路ID")
    private String traceId = MDC.get(SysConstants.MDC_KEY);

    @ApiModelProperty(value = "生成该响应结果的系统时间，格式为yyyyMMddHHmmssSSS")
    @JSONField(format = "yyyyMMddHHmmssSSS")
    private LocalDateTime localDateTime = LocalDateTime.now();

    public ResponseStatus(String code, String message) {
        this.code = code;
        this.message = message;
    }

    public ResponseStatus(ResponseCodeEnum responseCodeEnum) {
        this.code = responseCodeEnum.getCode();
        this.message = responseCodeEnum.getMessage();
    }

    public ResponseStatus(ResponseCodeEnum responseCodeEnum, T data) {
        this.code = responseCodeEnum.getCode();
        this.message = responseCodeEnum.getMessage();
        this.data = data;
    }

    public static <T> ResponseStatus<T> success() {
        return new ResponseStatus<>(ResponseCodeEnum.SUCCESS);
    }

    public static <T> ResponseStatus<T> success(T data) {
        return new ResponseStatus<>(ResponseCodeEnum.SUCCESS, data);
    }

    public static <T> ResponseStatus<T> success(ResponseCodeEnum responseCodeEnum, T data) {
        return new ResponseStatus<>(responseCodeEnum, data);
    }

    public static <T> ResponseStatus<T> failure() {
        return new ResponseStatus<>(ResponseCodeEnum.SYSTEM_EXCEPTION);
    }

    public static <T> ResponseStatus<T> failure(ResponseCodeEnum responseCodeEnum) {
        return new ResponseStatus<>(responseCodeEnum);
    }

}
